<template>
  <div>
    <!-- 搜索栏 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="图书名称">
              <el-input v-model="formInline.username" placeholder="请输入图书名称"></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="formInline.status" placeholder="请选择状态">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
              </el-select>
            </el-form-item>
            <!-- 开始时间 -->
            <el-form-item class="block">
              <span class="demonstration">创建时间</span>
              <el-date-picker
                v-model="formInline.begin"
                type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
        <!-- 结束时间 -->
            <el-form-item class="block">
              <span class="demonstration">创建时间</span>
              <el-date-picker
                v-model="formInline.end"
                type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="onSubmit" class="el-icon-search">查询</el-button>
              <!-- 新增图书 -->
              <el-button type="primary" @click="openAddWindow()" class="addButton el-icon-plus">新增用户</el-button>
            </el-form-item>
    </el-form>

    <!-- 主体表格-->
    <el-table :data="userList" style="width: 100%" border>
      <el-table-column prop="username" label="用户名" width="180"></el-table-column>
      <el-table-column label="头像" width="180">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" width="70" height="50" />
          {{ scope.toJSONString }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="180">
        <template slot-scope="scope">
          {{ scope.row.status === 1 ? "启用" : "已禁用"}}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="180"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="danger" @click="del(scope.row)" class="el-icon-delete" size="mini">删除</el-button>
          <el-button type="warning" @click="updateStatus(scope.row)" class="el-icon-mouse" size="mini">
            {{ scope.row.status === 1 ? "禁用" : "启用"}}
          </el-button>
          <el-button type="primary" @click="updateWindow(scope.row)" class="el-icon-edit" size="mini">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
  <div class="user">
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[5, 8, 10, 15, 20]"
      :page-size="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>

  <!-- 编辑页面 -->
  <el-dialog title="编辑用户" :visible.sync="updateDialog">
  <el-form :model="updateUser">
    <el-form-item label="用户名">
      <el-input v-model="updateUser.username" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="头像">
      <el-input v-model="updateUser.avatar" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="状态">
      <el-select v-model= "updateUser.status"  placeholder="请选择状态">
        <el-option label="启用" value="1"></el-option>
        <el-option label="禁用" value="0"></el-option>
      </el-select>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="updateDialog = false">取 消</el-button>
    <el-button type="primary" @click="goUpdateUser()">确 定</el-button>
  </div>
</el-dialog>

<!-- 新增页面 -->
  <el-dialog title="新增用户" :visible.sync="addDialog">
  <el-form :model="addUser">
    <el-form-item label="用户名">
      <el-input v-model="addUser.username" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="头像">
      <el-input v-model="addUser.avatar" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="状态">
      <el-select v-model= "addUser.status"  placeholder="请选择状态">
        <el-option label="启用" value="1"></el-option>
        <el-option label="禁用" value="0"></el-option>
      </el-select>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="addDialog = false">取 消</el-button>
    <el-button type="primary" @click="goAddUser()">确 定</el-button>
  </div>
</el-dialog>
<!-- 文件上传 -->
<el-upload
  class="avatar-uploader"
  action="http://localhost:8080/common"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload">
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

  </div>
</template>

<script>
import { getAllUserPage, deleteUserById, updateStatus, getUserById, upload, addUser, updateUserById } from '@/api/user.js'
export default {
  name: 'UserPage',
  data () {
    return {
      userList: [],
      page: 1,
      pageSize: 5,
      total: null,
      updateDialog: false, // 编辑窗口
      addDialog: false, // 新增窗口
      updateUser: {},
      addUser: {},
      imageUrl: '',
      formInline: {
        username: '',
        status: '',
        begin: '',
        end: ''
      }
    }
  },
  async created () {
    this.getUserPage()
  },

  methods: {
    // 新增窗口
    openAddWindow () {
      this.addDialog = true
    },
    // 新增用户
    async goAddUser () {
      await addUser(this.addUser.username, this.addUser.avatar, this.addUser.status)
      this.addUser = {}
      this.getUserPage()
      this.addDialog = false
    },
    // 条件查询
    onSubmit () {
      this.getUserPage()
    },
    // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 文件上传成功时的钩子
    async handleAvatarSuccess (res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      const res2 = await upload(file)
      this.imageUrl = res2.data
    },
    // 编辑窗口
    async updateWindow (row) {
      this.updateDialog = true
      const res = await getUserById(row.id)
      this.updateUser = res.data
    },
    // 编辑用户
    async goUpdateUser () {
      await updateUserById(this.updateUser.id, this.updateUser.username, this.updateUser.avatar, this.updateUser.status)
      this.getUserPage()
      this.updateDialog = false
    },
    // 修改用户状态
    updateStatus (row) {
    // row.status为1，说明要禁用，
      if (row.status === 1) {
        this.$confirm('确定要禁用该员工吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
        // 发送禁用请求，修改status为0
          await updateStatus(0, row.id)
          this.getUserPage()
          this.$message({
            type: 'success',
            message: '操作成功'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消禁用'
          })
        })
      }
      // row.status为0，说明要启用，
      if (row.status === 0) {
        this.$confirm('确定要启用该员工吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
        // 发送启用请求，修改status为1
          await updateStatus(1, row.id)
          this.getUserPage()
          this.$message({
            type: 'success',
            message: '取消启用'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '操作取消'
          })
        })
      }
      this.getUserPage()
    },
    // 删除用户
    del (row) {
      this.$confirm('此操作将永久删除该用户信息，您确定?', '提示', {
        confirmButtonText: '继续删除',
        cancelButtonText: '取消删除',
        type: 'warning'
      }).then(async () => {
        await deleteUserById(row.id)
        this.getUserPage()
        this.$message({
          type: 'success',
          message: '删除成功喽'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    },
    // 用户信息分页查询
    async getUserPage () {
      const res = await getAllUserPage(this.page, this.pageSize, this.formInline.username, this.formInline.status, this.formInline.begin,
        this.formInline.end)
      this.userList = res.data.records
      this.total = res.data.total
    },
    // 每页条数改变时触发
    handleSizeChange (pageSize) {
      this.pageSize = pageSize
      this.getUserPage()
    },

    // 当前页码改变时触发
    handleCurrentChange (page) {
      this.page = page
      // 调用分页查询
      this.getUserPage()
    }
  }
}
</script>

<style lang="less" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
